package com.example.yeujian5.yuejian5.fragment;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.example.yeujian5.yuejian5.Listenner.PictureListener;
import com.example.yeujian5.yuejian5.R;
import com.example.yeujian5.yuejian5.adapter.PictureAdapter;
import com.example.yeujian5.yuejian5.bean.PictureBean;
import com.example.yeujian5.yuejian5.model.PictureModel;

import static android.app.Activity.RESULT_OK;
import java.util.List;



public class PictureFragment extends Fragment implements PictureListener {
    private RecyclerView recyclerView;
    private Button select_btn_takePhoto;
    private ImageView reg_headPhoto;
    List<PictureBean> list;

    private String[] specialname;

    private static final int IMAGE_REQUEST_CODE = 0;
    private final int FILE_REQUEST_CODE_PICTURE = 1;

    private final int TAKE_PICTURE = 2;


    private static final String IMAGE_FILE_NAME = "header.jpg";

    private static final String TAG = "UploadFragment";



    public static final int CHOOSE_PHOTO = 3;
    private String currentspecial;
    private String path=null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_picture, container, false);
        initRecyclerView(view);
        PictureModel model=new PictureModel();
        model.getPhotoList("id","title",this);
        return  view;
    }

    public  void initRecyclerView(View view){
        recyclerView=(RecyclerView) view.findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        select_btn_takePhoto = (Button) view.findViewById(R.id.select_btn_takePhoto);
        reg_headPhoto = (ImageView) view.findViewById(R.id.reg_headPhoto);
        select_btn_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context=getActivity();
                final Context dialogContext = new ContextThemeWrapper(context,
                        android.R.style.Theme_Light);
                String cancel = "返回";
                String[] choices;
                choices = new String[2];
                choices[0] = getString(R.string.take_photo);
                choices[1] = getString(R.string.pick_photo);
                final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
                        android.R.layout.simple_list_item_1, choices);

                final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                        dialogContext);
                builder.setTitle(R.string.attachToContact);
                builder.setSingleChoiceItems(adapter, -1,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                switch (which) {
                                    case 0: {

                                        break;
                                    }
                                    case 1:
                                        Intent intent = new Intent("android.intent.action.GET_CONTENT");
                                        intent.setType("image/*");
                                        startActivityForResult(intent, CHOOSE_PHOTO);
                                        break;
                                }
                            }
                        });
                builder.setNegativeButton(cancel,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }

                        });
                builder.create().show();
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    Uri uri = data.getData();
                    reg_headPhoto.setImageURI(uri);
                    ContentResolver cr=getActivity().getContentResolver();
                    Cursor cursor = cr.query(uri,null,null,null,null);
                    cursor.moveToFirst();
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
                break;
            default:
                break;
        }
        super.onActivityResult( requestCode, resultCode, data);
    }

    String imagePath = null;

    @TargetApi(19)
    private void handleIMageOnKitKat(Intent data) {
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getActivity() , uri)){
            //如果是document类型的URI，则使用document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID +"=" +id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                imagePath = getImagePath(contentUri ,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果不是document类型的URI，则使用普通方式处理
            imagePath = getImagePath(uri , null);
        }
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if (imagePath!=null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            reg_headPhoto.setImageBitmap(bitmap);
        }else {
            Toast.makeText(getContext(), "未得到图片", Toast.LENGTH_SHORT).show();
        }
    }

    private String getImagePath(Uri uri, String selection) {
     //   String path = null;
        Cursor cursor = getActivity().getContentResolver().query(uri , null , selection , null , null);
//        cursor.moveToFirst();
//        Cursor cursor = getContext().getContentResolver().query(uri , null , selection , null , null);
        if (cursor!=null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleIMageBeforKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri , null);
        displayImage(imagePath);
    }


    @Override
    public void onResponse(List<PictureBean> listBeen) {
        list=listBeen;
        recyclerView.setAdapter(new PictureAdapter(getActivity(),list));
    }

    @Override
    public void onFail(String msg) {
        Toast.makeText(getActivity(), "fail"+msg, Toast.LENGTH_SHORT).show();
    }


}